﻿using Autofac;
using Autofac.Extensions.DependencyInjection;
using DDD.Application;
using DDD.Infrastructure;
using DDD.Infrastructure.RepositoryFramework;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;

namespace DDD.Presentation
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<DDDContext>(options =>
                 options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddTransient(typeof(IPersonService), typeof(PersonService));

            services.AddMvc();

            var builder = new ContainerBuilder();
            builder.RegisterType<DDDContext>().As<IDbContext>().InstancePerLifetimeScope();
            //builder.Register<IDbContext>(c => new DDDContext(Configuration.GetConnectionString("DefaultConnection"))).InstancePerLifetimeScope();
            builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>)).InstancePerLifetimeScope();



            builder.Populate(services);
            var container = builder.Build();
            return container.Resolve<IServiceProvider>();



        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();


        }
    }
}
